﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Background;
using Xiaowei.Diagnostics;

namespace Xiaowei.Helpers
{
    class KeepConnection
    {
        private const string BackgroundTriggerName = "KeepConnectionBackgroundTrigger";
        public static void RequestAccess()
        {
            Debug.WriteLine("RequestAccess");
            RequestRelease();
            var builder = new BackgroundTaskBuilder()
            {
                Name = BackgroundTriggerName,
            };
            builder.SetTrigger(new TimeTrigger(15,false));
            SystemCondition condition = new SystemCondition(SystemConditionType.InternetAvailable);
            builder.AddCondition(condition);
            builder.IsNetworkRequested = true;
            builder.Register();
            Debug.WriteLine("RequestAccess End");
        }

        public static void RequestRelease()
        {
            BackgroundTaskRegistration.AllTasks.Values
                  .Where(task => task.Name == BackgroundTriggerName)
                  .ToList()
                  .ForEach(task => task.Unregister(true));
        }

        public async static void OnBackgroundTask(BackgroundActivatedEventArgs args)
        {
            if(args?.TaskInstance.Task.Name == BackgroundTriggerName)
            {
                BackgroundTaskDeferral deferral = args.TaskInstance.GetDeferral();
                Debug.WriteLine("Keep Connection triggered");
                Services.XiaoweiAI.Instance.BeatHeart();
                deferral.Complete();
            }
        }
    }
}
